<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="!hasLogin || empty === true" class="empty">
			<image src="/static/state-cartempty.jpg" mode="aspectFit"></image>
			<view v-if="hasLogin" class="empty-tips">
				购物车空空如也
				<navigator class="navigator" v-if="hasLogin" url="home" open-type="switchTab">随便逛逛</navigator>
			</view>
			<view v-else class="empty-tips">
				购物车空空如也
				<view class="navigator" @click="navToLogin">去登陆</view>
			</view>
		</view>
		<view v-else class="cart_box">
			<!-- 列表 -->
			<view class="cart-list">
				<block v-for="(item, index) in cartList" :key="item.goodsid">
					<view class="cart-item" :class="{ 'b-b': index !== cartList.length - 1 }">
						<view class="image-wrapper" @click="toDetail(item.goodsid)">
							<image
								:src="item.logo"
								:class="[item.loaded]"
								mode="aspectFill"
								lazy-load
								@load="onImageLoad('cartList', index)" 
								@error="onImageError('cartList', index)"
							></image>
							<view class="mallicon icon-xuanzhong2 checkbox" :class="{ checked: item.checked }" @click.stop="check('item', index,item)"></view>
						</view>
						<view class="item-right">
							<text class="clamp title" @click="toDetail(item.goodsid)">{{ item.title }}</text>
							<view class="attr-box">
								<text class="attr">{{ item.goods_spec }}</text>
								<text class="attr"  v-if="item.number_stock == 0" style="color: red;">（无货）</text>
							</view>

							<view class="price-box">
								<text class="price">¥{{ item.price_market }}</text>
								<uni-number-box
									class="step"
									:min="1"
									:max="item.number_stock"
									:value="item.total > item.number_stock ? item.number_stock : item.total"
									:isMax="item.total >= item.number_stock ? true : false"
									:isMin="item.total === 1"
									:index="index"
									@eventChange="numberChange(item,$event)"
								></uni-number-box>
							</view>
						</view>
						<image src="../../static/icon_delete.png" class="del-btn" @click="deleteCartItem(item,index)"></image>
					</view>
				</block>
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="checkbox">
					<image :src="allChecked ? '/static/selected.png' : '/static/select.png'" mode="aspectFit" @click="check('all',cartList)"></image>
					<view class="selected-all-btn" @click="check('all',cartList)">全选</view>
				</view>
				<block v-if="!isDelete">
					<view class="total-box">
						<text class="price">合计：¥ {{ total }}</text>
					</view>
					<button type="primary" class="no-border confirm-btn" @click="createOrder">去结算（{{ cartNum }}）</button>
				</block>
				<button type="primary" class="no-border confirm-btn" v-if="isDelete" @click="deleteCartItems()">删除商品</button>
			</view>
		</view>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import uniNumberBox from '@/components/uni-number-box.vue';
export default {
	components: {
		uniNumberBox
	},
	data() {
		return {
			timestamp :(new Date()).getTime(),
			total: 0, //总价格
			allChecked: false, //全选状态  true|false
			empty: false, //空白页现实  true|false
			cartList: [],
			isDelete: false,
			// #ifdef MP
			editText:"编辑",
			// #endif
		};
	},
	onLoad() {
		// if (this.hasLogin) {
			// this.loadData();
		// }
	},
	onShow() {
		// if (this.hasLogin) {
			this.cartList = []
			this.loadData();
		// }
	},
	watch: {
		//显示空白页
		cartList(e) {
			let empty = e.length === 0 ? true : false;
			if (this.empty !== empty) {
				this.empty = empty;
			}
		},
		hasLogin(e) {
			if (this.hasLogin) {
				this.loadData();
			}
		}
	},
	computed: {
		...mapState(['hasLogin']),
		cartNum() {
			let list = this.cartList;
			let num = 0;
			list.forEach(item => {
				if (item.checked === true) {
					num++;
				}
			});
			return num;
		}
	},
	onNavigationBarButtonTap() {
		// #ifdef APP-PLUS
		var webView = this.$mp.page.$getAppWebview();
		// https://uniapp.dcloud.io/collocation/pages?id=app-titlenview-searchinput
		// 动态修改原生导航栏: https://ask.dcloud.net.cn/article/35374
		let str = this.isDelete ? '编辑' : '完成';
		webView.setTitleNViewButtonStyle(0, {
			text: str
		});
		this.isDelete = !this.isDelete;
		// #endif
	},
	methods: {
		// #ifdef MP
		editCart(){
			this.isDelete = !this.isDelete;
			this.editText = this.isDelete ? '编辑' : '完成';
		},
		// #endif
		//请求数据
		loadData() {
			this.$Request.get(this.$api.prodect.myCart).then(
				res => {
					this.cartList = []
					let cartList = res.data.data.map(item => {
						item.checked = false;
						// item.logo = item.logo+'?t='+this.timestamp
						return item;
					});
					this.cartList = cartList;
					this.calcTotal(); //计算总价
				},
				err => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
					console.log('err: ' + JSON.stringify(err));this.$utils.showMsg(err.data.info);
				}
			);
		},
		//监听image加载完成
		onImageLoad(key, index) {
			this.$set(this[key][index], 'loaded', 'loaded');
		},
		//监听image加载失败
		onImageError(key, index) {
			this[key][index].DefaultPicURL = '/static/errorImage.jpg';
		},
		navToLogin() {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		},
		//选中状态处理
		check(type, index,vm) {
			let that = this;
			console.log('选中状态处理',type, index)
			
			if (type === 'item') {
				if(vm.number_stock == 0){
					console.log('无货',vm)
					that.$utils.showMsg('暂无库存')
					that.cartList[index].checked = false;
				}else{
					that.cartList[index].checked = !that.cartList[index].checked;
				}
			} else {
				const list = that.cartList;
						let checked = !that.allChecked;
				list.forEach(item => {
					if(item.number_stock == 0){
						that.$utils.showMsg('有无库存商品，请手动选择商品')
						checked = !that.allChecked;
						item.checked = false;
						return
					}else{
						item.checked = checked;
						that.allChecked = checked;
					}
				});
				// const checked = !that.allChecked;
				// list.forEach(item => {
				// 	item.checked = checked;
				// });
				// that.allChecked = checked;
			}
			that.calcTotal(type);
		},
		//数量
		numberChange(vm,data) {
			// id: "164"
			// total: 20
			// 旧
			// console.log('total: ' + data.number);
			// this.cartList[data.index].total = data.number;
			// this.calcTotal();
			// 新
			console.log(vm,data,'数量加减: ',this.cartList);
			let needData = {
				id: vm.id,
				total: data.number
			}
			let dataIndex = data.index;
			this.cartList[dataIndex].total = data.number;
			this.$Request.post(this.$api.prodect.updateCart,needData).then(
				res => {
					this.calcTotal(); //计算总价
				},
				err => {
					console.log('err: ' + JSON.stringify(err));this.$utils.showMsg(err.data.info);
					// 其他页面都是code为1是请求成功,这个页面是0是返回成功,所以我在错误返回也调用方法
					this.cartList[data.index].total = data.number;
					this.calcTotal(); //计算总价
				}
			);
		},
		deleteCartItem(vm,index){
			let that =this;
			uni.showModal({
				content: '确认删除该商品吗？',
				success: e => {
					if (e.confirm) {
						// 旧,模拟删除
						// let list = that.cartList;
						// let row = list[index];
						
						// that.cartList.splice(index, 1);
						// that.calcTotal();
						// 新，接口删除
						console.log('删除购物车',vm,index)
						let needData = {
							ids:[]
							}
							needData.ids.push(vm.id)
						that.$Request.post(that.$api.prodect.removeCart,needData).then(
							res => {
								this.cartList = []
								that.loadData(); //计算总价
							},
							err => {
								console.log('err: ' + JSON.stringify(err));this.$utils.showMsg(err.data.info);
							}
						);
					}
				}
			});
		},
		//批量删除
		deleteCartItems() {
			let list = [];
			this.cartList.forEach((v, k) => {
				console.log('k: ' + k);
				if (this.cartList[k].checked === false) {
					list.push(this.cartList[k]);
				}
			});

			if (this.cartList.length === list.length) {
				this.$utils.showMsg('请选择商品');
				return false;
			}
			uni.showModal({
				content: '确认删除选中商品？',
				success: e => {
					if (e.confirm) {
						this.cartList = list;
						this.calcTotal();
					}
				}
			});
		},

		//计算总价
		calcTotal() {
			let list = this.cartList;
			if (list.length === 0) {
				this.empty = true;
				return;
			}
			let total = 0;
			let checked = true;
			list.forEach(item => {
				console.log('这里是计算总价',item)
				if (item.checked === true) {
					total += Number(item.price_market) * Number(item.total);
				} else if (checked === true) {
					checked = false;
				}
			});
			console.log('total: ' + total);
			this.allChecked = checked;
			this.total = Number(total.toFixed(2));
		},
		//创建订单
		createOrder() {
			let list = this.cartList;
			let goodsData = [];
			list.forEach(item => {
				if (item.checked) {
					console.log('dnwioahdiauowhdiuawdada5165468',item)
					item.cart_ids = item.id
					goodsData.push(item);
				}
			});
			uni.setStorageSync('goodData', goodsData);
			console.log('创建订单创建订单创建订单',goodsData)
			// //为了模拟数据，正常项目里按照业务传值
			uni.navigateTo({
				// 订单页面拿的是缓存
				url: '/pages/order/placeOrder'
			});
		},
		toDetail(vm){
			console.log(9995465,vm)
			uni.navigateTo({
				url: `/pages/product/detail?goods=${this.$utils.putExtra(vm)}`
			})
		}
	}
};
</script>

<style lang="scss">
.container {
	padding-bottom: 134upx;

	/* 空白页 */
	.empty {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100vh;
		padding-bottom: 100upx;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		background: #f5f5f5;

		image {
			width: 430rpx;
			height: 430rpx;
			margin-bottom: 30upx;
		}

		.empty-tips {
			font-size: $font-lg + 2upx;
			font-weight: 700;
			color: $uni-color-primary;

			.navigator {
				color: $font-color-white;
				font-size: $font-base;
				font-weight: 100;
				margin-left: 36rpx;
				background-color: $uni-color-primary;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-top: 60rpx;
				width: 160rpx;
				height: 64rpx;
				border-radius: 50upx;
			}
		}
	}
}

/* 购物车列表项 */
.cart-item {
	display: flex;
	position: relative;
	padding: 30upx 40upx;

	.image-wrapper {
		width: 220upx;
		height: 220upx;
		flex-shrink: 0;
		position: relative;

		image {
			border-radius: 8upx;
		}
	}

	.checkbox {
		position: absolute;
		left: -16upx;
		top: -16upx;
		z-index: 8;
		font-size: 44upx;
		line-height: 1;
		padding: 4upx;
		color: $font-color-disabled;
		background: #fff;
		border-radius: 50px;
	}
	.del-btn{
		height: 60rpx;
		width: 60rpx;
		margin-top: -6rpx;
		margin-right: -40rpx;
	}
	.item-right {
		display: flex;
		flex-direction: column;
		flex: 1;
		position: relative;
		padding-left: 30upx;

		.title,
		.price {
			word-wrap: break-word;
			word-break: break-all;
			white-space: pre-wrap;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			line-height: 1.6;
		}
		.attr-box {
			flex: 1;
			display: flex;
			flex-direction: row;

			.attr {
				font-size: $font-sm + 2upx;
				color: $font-color-light;
				height: 50upx;
				line-height: 50upx;
				margin-right: 20rpx;
			}
		}
		.price-box {
			flex: 1;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			.price {
				height: 50upx;
				line-height: 50upx;
			}

			.step {
			}
		}
	}
}

/* 底部栏 */
.action-section {
	/* #ifdef H5 */
	margin-bottom: 100upx;
	/* #endif */
	position: fixed;
	bottom: 0rpx;
	z-index: 95;
	display: flex;
	align-items: center;
	width: 750upx;
	height: 100upx;
	padding: 0 30upx;
	background: rgba(255, 255, 255, 0.9);
	box-shadow: 0 0 10upx 0 rgba(0, 0, 0, 0.5);

	.checkbox {
		height: 42upx;
		position: relative;

		image {
			width: 42upx;
			height: 100%;
			position: relative;
			z-index: 5;
		}
	}

	.selected-all-btn {
		position: absolute;
		left: 26upx;
		top: 0;
		z-index: 4;
		width: 0;
		height: 42upx;
		line-height: 42upx;
		padding-left: 38upx;
		font-size: $font-lg;
		color: $font-color-dark;
		width: 120upx;
	}

	.total-box {
		flex: 1;
		display: flex;
		flex-direction: row;
		text-align: left;
		font-size: $font-lg;
		margin-left: 120upx;

		.price {
			font-size: $font-lg;
			color: $font-color-dark;
		}
	}

	.confirm-btn {
		border-radius: 100px;
		height: 64rpx;
		line-height: 64rpx;
		font-size: $font-base + 2upx;
		background: $uni-color-primary;
		box-shadow: 1px 2px 5px rgba(217, 60, 93, 0.72);
		position: absolute;
		right: 30upx;
	}
}

/* 复选框选中状态 */
.action-section .checkbox.checked,
.cart-item .checkbox.checked {
	color: $uni-color-primary;
}
</style>
